package javaTest05.exercise01.udp;

import javaTest05.utils.FileUtils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class UdpServer {

    public static void main(String[] args) {
        try {
            InetAddress ip = InetAddress.getLocalHost();
            int port = 2468;

            DatagramSocket sever = new DatagramSocket(port,ip);
            System.out.println("服务端已启动,正在等待接收数据...");
            byte[] fileData = getFileDataFromRemote(ip,port,sever);//接收文件数据
            FileUtils.writeFileByByteArr(fileData,"src/javaTest05/resource/UdpRes.docx");//将字节数组写入文件
            sever.close();//关闭服务端

        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public static byte[] getFileDataFromRemote(InetAddress ip,int port,DatagramSocket sever) throws IOException {
        byte[] buffer = new byte[1024];//缓存

        DatagramPacket getPacket = new DatagramPacket(buffer,buffer.length);//创建接收数据报文

        ByteArrayOutputStream bOut = new ByteArrayOutputStream();

        while (true){
            sever.receive(getPacket);
            int byteLength = getPacket.getLength();

            if (byteLength < 1024 && new String(buffer).contains("file transfer end;")){//结束标志
                System.out.println("文件读取完成...");
                break;
            }

            bOut.write(buffer,0,byteLength);

            if (byteLength < 1024) {//如果缓存区未使用完,下次接受数据时会保留上一次缓存,造成数据污染
                buffer = new byte[1024];
                getPacket = new DatagramPacket(buffer, buffer.length);
            }
        }

        byte[] res = bOut.toByteArray();

        bOut.flush();
        bOut.close();

        return res;
    }
}
